package geppetto.phraseTable.phrase.feature.calc.local;

import geppetto.main.adaptation.AdaptationInfo;
import geppetto.phraseHMM.phraseExtraction.extractedphrase.ExtractedPhrasePairData;
import geppetto.phraseHMM.phraseExtraction.extractedphrase.data.AdaptationTypeData;
import geppetto.phraseHMM.phraseExtraction.extractedphrase.data.ScoreData;
import geppetto.phraseTable.phrase.Phrase;
import geppetto.phraseTable.phrase.feature.AbstractFeature;
import geppetto.phraseTable.phrase.feature.ProbabilityFeature;

import java.util.ArrayList;
import java.util.HashMap;

public class AdaptedPhraseProbabilityFeatureCalc implements AbstractFeatureCalc{

	protected final static String SCORE_HEADER = "score";
	protected final static String ADAPT_INFO_HEADER = "adaptation_type";
	protected final static String FEATURE = "adprob";
	HashMap<String, Double> type_weight = new HashMap<String, Double>();
	AdaptationInfo adaptationInfo;
	HashMap<String, Double> type_weights;
	protected int order;

	public AdaptedPhraseProbabilityFeatureCalc(HashMap<String, Double> type_weight, int order) {
		super();
		this.order = order;
		this.type_weight = type_weight;
	}

	public double[] calculateScoresForType(ArrayList<Phrase> phrases, String type) {
		double[] featureArray = new double[phrases.size()];
		double totalScore = 0;		
		for(int i = 0; i < featureArray.length; i++){
			Phrase p = phrases.get(i);
			double score = ((ScoreData)p.getData(SCORE_HEADER)).getScore();
			AdaptationTypeData adaptData = (AdaptationTypeData)p.getData(ADAPT_INFO_HEADER);
			totalScore+=score * adaptData.getValue(type);
		}

		for(int i = 0; i < featureArray.length; i++){
			Phrase p = phrases.get(i);
			double score = ((ScoreData)p.getData(SCORE_HEADER)).getScore();
			AdaptationTypeData adaptData = (AdaptationTypeData)p.getData(ADAPT_INFO_HEADER);	
			featureArray[i] = adaptData.getValue(type) * score / totalScore;
		}
		return featureArray;
	}

	@Override
	public void calculateFeature(ArrayList<Phrase> phrases) {
		for(int i = 0; i < phrases.size(); i++){
			Phrase p = phrases.get(i);

			AdaptationTypeData adaptData = (AdaptationTypeData)p.getData(ADAPT_INFO_HEADER);
			adaptData.normalize();
		}		

		double[] adaptedScores = new double[phrases.size()];
		for(int i = 0; i < adaptedScores.length; i++){
			adaptedScores[i] = 0;
		}

		for(String key : type_weight.keySet()){
			double[] scores = calculateScoresForType(phrases, key);
			for(int i = 0; i < adaptedScores.length; i++){
				adaptedScores[i] += scores[i] * type_weight.get(key);
			}
		}
		for(int i = 0; i < phrases.size(); i++){
			phrases.get(i)._features.addFeature(FEATURE,new ProbabilityFeature(adaptedScores[i]),order);
		}
	}
}
